package com.misty.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.misty.common.bean.Result;
import com.misty.common.constants.ResultEnum;
import com.misty.dao.domain.Tag;
import com.misty.dao.mapper.TagMapper;
import com.misty.admin.service.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cthulhu
 * @since 2022-11-21
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Resource
    private TagMapper tagMapper;


    /**
     *
     * @Param
     * @return
     * @Description 新增标签
     * @Date
     **/
    @Override
    public Result<?> saveTag(Tag tag) {
        tag.setCreateTime(LocalDateTime.now());
        tag.setUpdateTime(LocalDateTime.now());
        int insert = tagMapper.insert(tag);
        if(insert <= 0){
            Result.error(ResultEnum.FAILURE.getValue(),"新增标签失败！");
        }
        return Result.success(ResultEnum.SUCCESS.getValue(),"新增标签成功！");
    }

    /**
     *
     * @Param
     * @return
     * @Description 更新标签
     * @Date
     **/
    @Override
    public Result<?> updateTag(Tag tag) {
        tag.setUpdateTime(LocalDateTime.now());
        int update = tagMapper.updateById(tag);
        if(update <= 0){
            Result.error(ResultEnum.FAILURE.getValue(),"更新标签失败！");
        }
        return Result.success(ResultEnum.SUCCESS.getValue(),"更新标签成功！");
    }


    /**
     *
     * @Param
     * @return
     * @Description 删除标签
     * @Date
     **/
    @Override
    public Result<?> deleteTag(Integer tagId) {
        int delete = tagMapper.deleteById(tagId);
        if(delete <= 0){
            Result.error(ResultEnum.FAILURE.getValue(),"删除标签失败！");
        }
        return Result.success(ResultEnum.SUCCESS.getValue(),"删除标签成功！");
    }

    /**
     *
     * @Param
     * @return
     * @Description 分页查询标签
     * @Date
     **/
    @Override
    public Result<?> Page(Integer pageNum, Integer pageSize, String search
    ) {
        LambdaQueryWrapper<Tag> tagLambdaQueryWrapper = Wrappers.<Tag>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            tagLambdaQueryWrapper.like(Tag::getName, search);
        }
        Page<Tag> tagPage = tagMapper.selectPage(new Page<>(pageNum, pageSize),tagLambdaQueryWrapper);
        if(tagPage.getTotal() <= 0){
            Result.error(ResultEnum.FAILURE.getValue(),"分页查询标签失败！");
        }
        return Result.success(ResultEnum.SUCCESS.getValue(),"分页查询标签成功！",tagPage);
    }

}
